
package com.cmc.dao.hibernate;

import java.util.List;

import com.cmc.dao.hibernate.BaseDaoHibernate;
import com.cmc.model.RightRule;
import com.cmc.dao.RightRuleDao;

import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.criterion.Example;
import org.hibernate.criterion.MatchMode;
import org.springframework.orm.ObjectRetrievalFailureException;
import org.springframework.orm.hibernate3.HibernateCallback;

public class RightRuleDaoHibernate extends BaseDaoHibernate implements RightRuleDao {

    /**
     * @see com.cmc.dao.RightRuleDao#getRightRules(com.cmc.model.RightRule)
     */
    public List getRightRules(final RightRule rightRule) {
        //return getHibernateTemplate().find("from RightRule");

        /* Remove the line above and uncomment this code block if you want 
           to use Hibernate's Query by Example API.*/
        if (rightRule == null) {
            return getHibernateTemplate().find("from RightRule");
        } else {
            // filter on properties set in the rightRule
            HibernateCallback callback = new HibernateCallback() {
                public Object doInHibernate(Session session) throws HibernateException {
                    Example ex = Example.create(rightRule).ignoreCase().enableLike(MatchMode.ANYWHERE);
                    return session.createCriteria(RightRule.class).add(ex).list();
                }
            };
            return (List) getHibernateTemplate().execute(callback);
        }
    }

    /**
     * @see com.cmc.dao.RightRuleDao#getRightRule(Long id)
     */
    public RightRule getRightRule(final Long id) {
        RightRule rightRule = (RightRule) getHibernateTemplate().get(RightRule.class, id);
        if (rightRule == null) {
            log.warn("uh oh, rightRule with id '" + id + "' not found...");
            throw new ObjectRetrievalFailureException(RightRule.class, id);
        }

        return rightRule;
    }

    /**
     * @see com.cmc.dao.RightRuleDao#saveRightRule(RightRule rightRule)
     */    
    public void saveRightRule(final RightRule rightRule) {
        getHibernateTemplate().saveOrUpdate(rightRule);
    }

    /**
     * @see com.cmc.dao.RightRuleDao#removeRightRule(Long id)
     */
    public void removeRightRule(final Long id) {
        getHibernateTemplate().delete(getRightRule(id));
    }
}
